/*
 * @Author: wrngygy
 * @Date: 2025-07-01
 * @Description: Token 和用户状态管理
 */

import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

// 用户信息接口
interface UserInfo {
	id: number | string
	username: string
	nickname?: string
	email?: string
	avatar?: string
	permissions?: string[]
	roles?: string[]
}

export const useTokenStore = defineStore('tokenStore', () => {
	// 状态
	const token = ref<string | null>(localStorage.getItem('token'))
	const openid = ref<string | null>(localStorage.getItem('openid'))
  // 未登录提示登录
	const loginPrompt = ref<Boolean>(false)
  

	const refreshToken = ref<string | null>(localStorage.getItem('refreshToken'))
	const userInfo = ref<UserInfo | null>(null)
	const permissions = ref<string[]>([])   
	const roles = ref<string[]>([])

	// 计算属性
	const hasToken = computed(() => !!token.value)
	const isLoggedIn = computed(() => !!token.value)

	// 获取 token
	const getToken = () => {
		return token.value
	}

	// 获取用户权限
	const getPermissions = () => {
		return permissions.value
	}

	// 获取用户角色
	const getRoles = () => {
		return roles.value
	}

	// 设置 token
	const setToken = (newToken: string) => {
		token.value = newToken
		localStorage.setItem('token', newToken)
	}
  	// 设置 openid
	const setOpenid = (newOpenid: string) => {
		openid.value = newOpenid
		localStorage.setItem('openid', newOpenid)
	}
    	// 设置
	const setLoginPrompt = (newOpenid: Boolean) => {
		loginPrompt.value = newOpenid
	}

	// 设置刷新 token
	const setRefreshToken = (newRefreshToken: string) => {
		refreshToken.value = newRefreshToken
		localStorage.setItem('refreshToken', newRefreshToken)
	}

	// 设置用户信息
	const setUserInfo = (info: UserInfo) => {
		userInfo.value = info
	}

	// 清除 token 和用户信息
	const clearToken = () => {
		token.value = null
		refreshToken.value = null
		userInfo.value = null
		permissions.value = []
		roles.value = []
		localStorage.removeItem('token')
		localStorage.removeItem('refreshToken')
		localStorage.removeItem('userInfo')
	}

	// 初始化应用设置
	const initAppSettings = () => {
		// 从本地存储恢复用户信息
		const savedUserInfo = localStorage.getItem('userInfo')
		if (savedUserInfo && token.value) {
			try {
				const parsedUserInfo = JSON.parse(savedUserInfo)
				setUserInfo(parsedUserInfo)
			} catch (error) {
				console.error('解析用户信息失败:', error)
				clearToken()
			}
		}
	}

	// 检查是否有指定权限
	const hasPermission = (permission: string) => {
		return permissions.value.includes(permission)
	}

	// 检查是否有指定角色
	const hasRole = (role: string) => {
		return roles.value.includes(role)
	}

	return {
		// 状态
		token,
    openid,
    loginPrompt,

		refreshToken,
		userInfo,
		permissions,
		roles,

		// 计算属性
		hasToken,
		isLoggedIn,

		// 方法
		getToken,
		getPermissions,
		getRoles,
		setToken,
    setOpenid,
    setLoginPrompt,
		setRefreshToken,
		setUserInfo,
		clearToken,
		initAppSettings,
		hasPermission,
		hasRole,
	}
})
